package com.pactera.madp.cp.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.pactera.madp.common.core.exception.CheckedException;
import com.pactera.madp.common.core.util.SpringContextHolder;
import com.pactera.madp.cp.api.dto.track.BehaviorTrackDto;
import com.pactera.madp.cp.api.entity.*;
import com.pactera.madp.cp.common.enums.BehaviorTrackEnum;
import com.pactera.madp.cp.common.util.WxApiUtils;
import com.pactera.madp.cp.service.ICorpService;
import com.pactera.madp.cp.service.IWorkContactService;
import com.pactera.madp.cp.service.IWorkEmployeeService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public abstract class BaseBehaviorTrackServer {

    @Autowired
    private ICorpService corpService;

    /**
     * 事件处理
     * @param dto
     * @param workEmployeeService
     * @param workContactService
     * @param response
     * @throws Exception
     */
    public abstract void handleEvent(BehaviorTrackDto dto, IWorkEmployeeService workEmployeeService, IWorkContactService workContactService, HttpServletResponse response) throws Exception;

    /**
     *  基本事件处理
     * @param entity
     * @param workEmployeeService
     * @param workContactService
     * @param behaviorTrackServer
     * @param response
     * @throws Exception
     */
    @SneakyThrows
    public void baseHandleEvent(BehaviorTrackEntity entity, IWorkEmployeeService workEmployeeService,
                                IWorkContactService workContactService, BaseBehaviorTrackServer behaviorTrackServer,
                                HttpServletResponse response) throws Exception {

        //获取发送应用id
        String wxCorpId = corpService.getById(entity.getCorpId()).getWxCorpId();
//        Integer agentId = SendMsgAgentEnum.findByType(wxCorpId).getAgentId();
        Integer agentId = corpService.getWxSendMsgAgentIdByWxCorpId(wxCorpId);

        //数据组装
        Map data = baseBuildData(entity, workEmployeeService, workContactService, behaviorTrackServer);
        BehaviorTrackTextMsg msg = (BehaviorTrackTextMsg)behaviorTrackServer.getBehaviorTrackMsg(entity.getWxUserId(), agentId, "text", data);
        log.info("behaviorTrackTextMsg:{}",msg);
        //消息推送
        WxApiUtils.sendMsgToEmployee(msg, entity.getCorpId());
        log.info("消息发送完毕>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
    }

    /**
     * 获取事件处理器
     * @param event
     * @return
     */
    public static BaseBehaviorTrackServer selectHandler(String event){
        Class behaviorClass = BehaviorTrackEnum.findByType(event).getCls();
        BaseBehaviorTrackServer behaviorTrackService = (BaseBehaviorTrackServer)SpringContextHolder.getBean(behaviorClass);
        return behaviorTrackService;
    }

    /**
     * 基本数据组装
     * @param entity
     * @param workEmployeeService
     * @param workContactService
     * @param behaviorTrackServer
     * @return
     */
    protected Map baseBuildData(BehaviorTrackEntity entity,
                                IWorkEmployeeService workEmployeeService,
                                IWorkContactService workContactService,
                                BaseBehaviorTrackServer behaviorTrackServer){

        String errorMsg = "";

        Integer corpId = entity.getCorpId();
        String wxUserId = entity.getWxUserId();
        String externalUserId = entity.getWxExternalUserid();

        //查询成员信息
        WorkEmployeeEntity employeeEntity = workEmployeeService.getWorkEmployeeByCorpIdAndWxUserId(corpId, wxUserId);
        if(employeeEntity == null){
            errorMsg = "企业" + corpId + "成员" + wxUserId + "不存在";
            log.error(errorMsg);
            throw new CheckedException(errorMsg);
        }
        entity.setUsername(employeeEntity.getName());
        entity.setCorpId(employeeEntity.getCorpId());
        entity.setEmployeeId(employeeEntity.getId());

        //查询联系人信息
        WorkContactEntity contactEntity = workContactService.getOne(Wrappers.<WorkContactEntity>lambdaQuery()
                .eq(WorkContactEntity::getCorpId,corpId)
                .eq(WorkContactEntity::getWxExternalUserid,externalUserId),false);
        if(contactEntity == null) {
            errorMsg = "企业" + corpId + "外部联系人" + externalUserId + "不存在";
            log.error(errorMsg);
            throw new CheckedException(errorMsg);
        }
        entity.setExternalUsername(contactEntity.getName());
        entity.setContactId(contactEntity.getId());

        //消息内容构建
        String content = behaviorTrackServer.buildData(entity);
        log.info(content);

        Map data = new HashMap();
        data.put("content",content);

        return data;
    }

    /**
     * 业务数据组装
     * @param entity
     * @return
     */
    protected abstract String buildData(BehaviorTrackEntity entity);

    /**
     * 获取发送消息 默认为文本消息
     * @param userIds
     * @param agentId
     * @param msgType
     * @param data
     * @return
     */
    protected BehaviorTrackMsg getBehaviorTrackMsg(String userIds, Integer agentId, String msgType, Map data) {
        BehaviorTrackTextMsg msg = new BehaviorTrackTextMsg(userIds, agentId, msgType, data);
        return msg;
    }

    /**
     * 消息推送
     * @param msg
     * @param corpId
     */
    /*@Async
    protected void sendMsg(BehaviorTrackMsg msg, Integer corpId) {
        //获取token
        BehaviorTrackTextMsg textMsg = (BehaviorTrackTextMsg)msg;
        String accessToken = WxApiUtils.getAccessTokenAgent(corpId, Constant.SEND_MSG_AGENT_ID);
        String msgUrl = WxApiConst.API_ADD_MESSAGE.replace("ACCESS_TOKEN",accessToken);
        log.info("msgUrl:{}",msgUrl);
        log.info("msg:{}",textMsg);
        HttpUtil.post(msgUrl, JSONUtil.toJsonStr(textMsg));
    }*/

}
